package com.yanx.system.web.query;

import com.yanx.common.command.Executor;
import com.yanx.common.core.command.PageQryCommand;
import com.yanx.system.base.model.qo.SysDeptQo;
import com.yanx.system.base.model.vo.SysDeptVo;
import com.yanx.system.base.query.SysDeptListQry;
import com.yanx.system.web.model.vo.SysDeptTreeVo;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜单权限树查询
 *
 * @author: gotanks
 * @create: 2023-2-9
 */
@NoArgsConstructor
@AllArgsConstructor
public class SysDeptTreeListQry extends PageQryCommand<List<SysDeptTreeVo>> {
    private SysDeptQo dept;

    @Override
    public List<SysDeptTreeVo> execute(Executor executor) {
        List<SysDeptVo> sysDeptVos = executor.execute(new SysDeptListQry(dept));

        //转为树形结构
        List<SysDeptVo> returnList = (List<SysDeptVo>) SysMenuTreeByUserIdQry.getChildPerms(sysDeptVos);
//        List<Long> tempList = sysDeptVos.stream().map(SysDeptVo::getId).collect(Collectors.toList());
//        for (SysDeptVo menu : sysDeptVos) {
//            // 如果是顶级节点, 遍历该父节点的所有子节点
//            if (!tempList.contains(menu.getParentId())) {
//                recursionFn(sysDeptVos, menu);
//                returnList.add(menu);
//            }
//        }
        if (returnList.isEmpty()) {
            returnList = sysDeptVos;
        }
        return returnList.stream().map(SysDeptTreeVo::new).collect(Collectors.toList());

    }

    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t    子节点
     */
    private void recursionFn(List<SysDeptVo> list, SysDeptVo t) {
        // 得到子节点列表
        List<SysDeptVo> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDeptVo tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDeptVo> getChildList(List<SysDeptVo> list, SysDeptVo t) {
        return list.stream()
                .filter(m -> m.getParentId().longValue() == t.getId().longValue())
                .collect(Collectors.toList());
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDeptVo> list, SysDeptVo t) {
        return getChildList(list, t).size() > 0;
    }
}